//
//  ThirtyViewController.m
//  项目二
//
//  Created by rimi on 16/5/17.
//  Copyright © 2016年 objective. All rights reserved.
//

#import "ThirtyViewController.h"
/**< 新闻分类的个数 */
#define TITLE_COUNT _newsTitle.count

#define BUTTON_TAG 100
@interface ThirtyViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    CGFloat _buttonH;
    CGFloat _buttonW; /**< 标题按钮宽高 */
    NSArray *_newsTitle; /**< 新闻标题集合 */
    UIButton *_lastSelectedButton; /**< 记录前一次点击的标题按钮 */
}

@property (nonatomic, strong)  UIScrollView *newsTitleScroll; /**< 新闻标题 */

/**< 内容collection */
@property (nonatomic, strong)  UICollectionViewFlowLayout *flowout;
@property (nonatomic, strong)  UICollectionView *contentCollection;

@end

@implementation ThirtyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.view.backgroundColor = [UIColor whiteColor];
    [self initializeDataSource];
    [self initializeUserInterface];
}

#pragma mark - Initialize
- (void)initializeDataSource {
    _buttonW = kSCREEN_W * 0.2;
    _buttonH = 45;
    _newsTitle = @[@"头条", @"娱乐", @"热点", @"科技", @"金融", @"图片", @"时尚", @"军事", @"历史"];
}
- (void)initializeUserInterface {
    __weak typeof(self) weakSelf = self;
    // 关闭系统自动偏移
    self.automaticallyAdjustsScrollViewInsets = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    // 导航栏标题
    self.navigationItem.title = @"网易新闻";
    self.navigationController.navigationBar.barTintColor = RGB_COLOR(255, 97, 76, 1);
    
    // 设置标题属性
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    // 加载newsTitleScroll
    [self.view addSubview:self.newsTitleScroll];
    
    // 循环添加标题按钮
    [_newsTitle enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(_buttonW * idx, 0, _buttonW, _buttonH);
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:RGB_COLOR(170, 170, 170, 1) forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        [button addTarget:self action:@selector(respondToButton:) forControlEvents:UIControlEventTouchUpInside];
        // 设置tag
        button.tag = BUTTON_TAG + idx;
        [weakSelf.newsTitleScroll addSubview:button];
        
        // 判断，如果是第一个按钮
        if (idx == 0) {
            [self updateWith:button isSelected:YES];
        }
    }];
    
    // 加载内容视图
    [self.view addSubview:self.contentCollection];
}
#pragma mark - Events
- (void)respondToButton:(UIButton *)sender {
    [self updateWith:sender isSelected:YES];
}

#pragma mark - Update

// isSelected 用来判断是通过下面的collection来偏移newsTitleScorll还是通过直接滑动newsTitleScorll来偏移
- (void)updateWith:(UIButton *)button isSelected:(BOOL)isSelected {
    __weak typeof(self) weakSelf = self;
    // 判断前一次选择的按钮是否被选择，如果被选择，就让前一次的按钮样式归位
    if (_lastSelectedButton) {
        _lastSelectedButton.transform = CGAffineTransformIdentity;
        [_lastSelectedButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    _lastSelectedButton = button;
    //__weak typeof(self) weakSelf = self;
    // 为按钮标题添加动画效果
    [UIView animateWithDuration:0.1 animations:^{
        button.transform =CGAffineTransformMakeScale(1.3, 1.3); /**< 放大 */
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    } completion:^(BOOL finished) {
        // 获取当前按钮是第几个
        NSInteger idx = button.tag - BUTTON_TAG;
        
        // 如果当前的按钮位于第2个到倒数第2个之间, 将按钮置于中间
        if (idx > 2 && idx < TITLE_COUNT - 2) {
            [weakSelf.newsTitleScroll setContentOffset:CGPointMake((idx - 2) * _buttonW, 0) animated:YES];
        }
        // 如果点击前两个按钮，偏移量置零
        else if (idx >= 0 && idx <= 2) {
            [weakSelf.newsTitleScroll setContentOffset:CGPointZero animated:YES];
        }
        // 如果点击后两个按钮
        else if (idx >= TITLE_COUNT - 2) {
            [weakSelf.newsTitleScroll setContentOffset:CGPointMake(_buttonW * (TITLE_COUNT - 5), 0) animated:NO];
        }
        
        // 动画执行完后更新内容的偏移
        if (isSelected) {
            weakSelf.contentCollection.contentOffset = CGPointMake(idx * kSCREEN_W, 0);
        }
    }];
}
#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newsTitle.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reUse" forIndexPath:indexPath];
    cell.backgroundColor = [self specialRandomColor];
    return cell;
}

// 减速完成后让按钮也配置到当前的cell
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        
        // 获取按钮下标
        NSInteger index = scrollView.contentOffset.x / kSCREEN_W;
        NSInteger tag = index + BUTTON_TAG;
        
        // 取出对应tag的按钮
        UIButton *button = (UIButton *)[self.view viewWithTag:tag];
        
        [self updateWith:button isSelected:NO];
    }
}
#pragma mark - 获取随机颜色
- (UIColor *)specialRandomColor {
    
    CGFloat hue = arc4random() % 256 / 256.0 ;  //  0.0 to 1.0
    CGFloat saturation = arc4random() % 128 / 256.0 + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = arc4random() % 128 / 256.0 + 0.5;  //  0.5 to 1.0, away from black
    
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
#pragma mark - lazy load
- (UIScrollView *)newsTitleScroll {
    if (!_newsTitleScroll) {
        _newsTitleScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_W, 45)];
        _newsTitleScroll.backgroundColor = RGB_COLOR(242, 242, 242, 1);
        _newsTitleScroll.pagingEnabled = NO;
        // 滚动视图的内容大小
        _newsTitleScroll.contentSize = CGSizeMake(TITLE_COUNT * _buttonW, _buttonH);
    }
    return _newsTitleScroll;
}

- (UICollectionViewFlowLayout *)flowout {
    if (!_flowout) {
        // 获取按钮scroll的高度
        CGFloat height = CGRectGetMaxY(self.newsTitleScroll.frame);
        
        // 布局_flowout
        _flowout = [[UICollectionViewFlowLayout alloc]init];
        _flowout.itemSize = CGSizeMake(kSCREEN_W, kSCREEN_H - height);
        _flowout.minimumInteritemSpacing = 0;
        _flowout.minimumLineSpacing = 0;
        _flowout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _flowout;
}
- (UICollectionView *)contentCollection {
    if (!_contentCollection) {
        // 获取按钮scroll的高度
        CGFloat height = CGRectGetMaxY(self.newsTitleScroll.frame);
        _contentCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, height, kSCREEN_W, kSCREEN_H - height) collectionViewLayout:self.flowout];
        _contentCollection.dataSource = self;
        _contentCollection.delegate = self;
        _contentCollection.pagingEnabled = YES;
        _contentCollection.bounces = NO;
        // 注册cell原型
        [_contentCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reUse"];
    }
    return _contentCollection;
}
@end
